import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { Tab } from 'libs/db/src/model/tab.model';
import { TabDetail } from 'libs/db/src/model/tabDetail.model';
import { InjectModel } from 'nestjs-typegoose';
import { CreateTabItemDto } from './createTabItem.dto';

@Injectable()
export class TabService {
  constructor(
    @InjectModel(Tab)
    private readonly tabModel: ReturnModelType<typeof Tab>,
    @InjectModel(TabDetail)
    private readonly tabDetailModel: ReturnModelType<typeof TabDetail>,
  ) {}

  async create(collectionId: string, tab: CreateTabItemDto) {
    let id;
    const tabInSql = await this.findOne(tab.name, tab.url);

    if (tabInSql) {
      id = tabInSql.id;
    } else {
      const newTab = await this.tabModel.create(tab);
      id = newTab.id;
    }

    const detail = await this.tabDetailModel.findOne({
      collectionId,
      tabId: id,
    });

    if (detail) return;

    await this.tabDetailModel.create({
      collectionId,
      tabId: id,
    });
  }

  async remove(id: string) {
    const details = await this.tabDetailModel.find({
      tabId: id,
    });

    if (details.length >= 1) {
      return;
    }

    return await this.tabModel.remove({
      _id: id,
    });
  }

  async findOne(name: string, url: string): Promise<Tab | undefined> {
    return await this.tabModel.findOne({
      name,
      url,
    });
  }

  async findOneById(id: string): Promise<Tab | undefined> {
    return await this.tabModel.findById(id);
  }
}
